<?php namespace App\Controllers\Admin;

use \App\App;

class Setting extends App
{

    public function __construct()
    {
        parent::__construct();
        if (!$this->user) {
            showError("用户尚未登录，请登录后重新打开。", '', '无权限访问');
        }
        //$this->settingModel = new \App\Models\Setting();
    }

    public function index()
    {
        $this->view->settings = $this->setting->findAll();
        $this->view->title = "系统设置";
        $this->view->desc = "点击允许编辑，进行编辑操作。";
        $this->render('admin/setting/list', 'default');
    }

    public function add($id = '')
    {
        if ($id) {
            $this->view->setting = $this->setting->find($id);
        }

        $this->render('admin/setting/add');
    }

    public function save()
    {
        $pk = $this->request->post('pk');
        if ($pk) {
            $setting[$this->request->post('name')] = $this->request->post('value');
            $this->setting->update($pk, $setting);
        } else {
            $option = $this->request->post('options') ? json_encode(explode(",", $this->request->post('options'))) : '';

            $setting = [
                'id' => $this->request->post('id'),
                'name' => $this->request->post('name'),
                'desc' => $this->request->post('desc'),
                'value' => $this->request->post('value'),
                'type' => $this->request->post('type'),
                'options' => $option,
            ];

            $this->setting->save($setting);
            $pk = $this->db->insertID();
        }
        $this->showJson(['message' => '保存设置成功', 'pk' => $pk]);
    }

}
